//
//  ZUserMsgViewController.m
//  ZQLearn
//
//  Created by macfeel on 2019/4/21.
//  Copyright © 2019 macfeel. All rights reserved.
//
#import "ZFActionSheet.h"
#import "ZUserMsgViewController.h"
#import "UserMsgCell.h"
#import "ZNickAddSchoolLikeVC.h"
#import "ZJUsefulPickerView.h"
#import "GFAddressPicker.h"
#import "UICustomDatePicker.h"
#import "SHAddImgView.h"
@interface ZUserMsgViewController ()<UITableViewDelegate,UITableViewDataSource,STPickerSingleDelegate,GFAddressPickerDelegate,SHAddImgViewDelegate,UIImagePickerControllerDelegate,ZFActionSheetDelegate>

@property (nonatomic,strong)UITableView *tableView;

@property (nonatomic,strong)NSArray *titles;

@property (nonatomic,strong)GFAddressPicker *pickerView;

@property (nonatomic,strong)UIImageView *photo;

@end

@implementation ZUserMsgViewController

#define cellIdentifier @"usermsg"
//#define vCellIdentifier @"video"

-(UITableView *)tableView{
    
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0 , 0, ScreenWidth , ScreenHeight -ScreenHeightFlex) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
//        _tableView.rowHeight = 55;
        _tableView.backgroundColor = kBackgroundColor;
        [_tableView registerNib:[UINib nibWithNibName:@"UserMsgCell" bundle:nil] forCellReuseIdentifier:cellIdentifier];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.tableFooterView = [UIView new];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setItemWithTitle:@"个人信息" textColor:kNavigationTitleColor fontSize:18 itemType:center];
    self.titles = @[@"头像",@"昵称",@"手机号",@"出生年月",@"性别",@"地址",@"详细地址",@"学校",@"年级",@"爱好",];
    [self.view addSubview:self.tableView];
    
}

- (void)viewWillAppear:(BOOL)animated{
    
    
    [super viewWillAppear:animated];
    
//    [UserInfoSave shareInstance].nickName = [[NSUserDefaults standardUserDefaults]objectForKey:@"nickName"];
//    [UserInfoSave shareInstance].phone = [[NSUserDefaults standardUserDefaults]objectForKey:@"phone"];
//    YYLog(@"%@", [UserInfoSave shareInstance].phone);
//    [UserInfoSave shareInstance].birthday = [[NSUserDefaults standardUserDefaults]objectForKey:@"birthday"];
//    [UserInfoSave shareInstance].gender = [[NSUserDefaults standardUserDefaults]objectForKey:@"gender"];
//    [UserInfoSave shareInstance].area = [[NSUserDefaults standardUserDefaults]objectForKey:@"area"];
//    [UserInfoSave shareInstance].address = [[NSUserDefaults standardUserDefaults]objectForKey:@"address"];
//    [UserInfoSave shareInstance].school = [[NSUserDefaults standardUserDefaults]objectForKey:@"school"];
//    [UserInfoSave shareInstance].grade = [[NSUserDefaults standardUserDefaults]objectForKey:@"grade"];
//    [UserInfoSave shareInstance].hobby = [[NSUserDefaults standardUserDefaults]objectForKey:@"hobby"];
//    YYLog(@"奇怪:%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"hobby"]);
//    YYLog(@"8888%@jjjj",[UserInfoSave shareInstance].hobby);
    //头像
//    NSData *data = [[NSUserDefaults standardUserDefaults]objectForKey:@"head"];
//    if (data) {
//        self.photo.image = [UIImage imageWithData:data];
//    }
    
     [self.tableView reloadData];
    
}




#pragma mark - datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UserMsgCell *  cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    if (indexPath.row==0) {
        cell.img.hidden = false;
        cell.img.layer.cornerRadius = 25.f;
        cell.img.layer.masksToBounds = YES;
        cell.detailLab.hidden = YES;
        self.photo = cell.img;
        NSData *data = [[NSUserDefaults standardUserDefaults]objectForKey:@"head"];
        if (data) {
            self.photo.image = [UIImage imageWithData:data];
        }
    }
    cell.nameLab.text = self.titles[indexPath.row];
    switch (indexPath.row) {
        case 1:
        {
            cell.detailLab.text = [UserInfoSave shareInstance].nickName;
        }
            break;
        case 2:
        {
            cell.detailLab.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"phone"];
        }
            break;
        case 3:
        {
            cell.detailLab.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"birthday"];
        }
            break;
        case 4:
        {
            cell.detailLab.text = [[UserInfoSave shareInstance].gender isEqualToString:@"1"]?@"男":@"女";
            
        }
            break;
        case 5:
        {
//            cell.detailLab.text = [UserInfoSave shareInstance].area;
             cell.detailLab.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"area"];
        }
            break;
        case 6:
        {
            cell.detailLab.text =[[NSUserDefaults standardUserDefaults]objectForKey:@"address"];
        }
            break;
        case 7:
        {
            cell.detailLab.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"school"];
        }
            break;
        case 8:
        {
            cell.detailLab.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"grade"];
        }
            break;
        case 9:
        {
            cell.detailLab.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"hobby"];
        }
            break;
            
        default:
            break;
    }
    return cell;
}


#pragma delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==0) {
        return 80.f;
    }
    return 55.f;
}


#pragma mrak -
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^{
        NSLog(@"取消");
    }];
}

#pragma mark - 照片处理代理

///进行拍照的上传
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    UIImage *img = info[UIImagePickerControllerEditedImage];
    self.photo.image = img;
    NSArray *array = @[img];
    
    /* 把图片转成NSData类型的数据来保存文件 */
    NSData *data;
    
    /* 判断图片是不是png格式的文件 */
    if (UIImagePNGRepresentation(img))
    {
        /* 返回为png图像 */
        data = UIImagePNGRepresentation(img);
    }
    else
    {
        /* 返回为JPEG图像 */
        data = UIImageJPEGRepresentation(img, 1.0);
    }
    
    /* 保存 */
//    [LoginState saveUserInfoToUserdefaults:UserHeadImage andInfo:data];
    //        将图片显示在界面上
    self.photo.image = [UIImage imageWithData:data];
   
    [[NSUserDefaults standardUserDefaults]setObject:data forKey:@"head"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    
    ////需要明确头像上传的相关具体参数
//    NSDictionary *dict = @{@"userInfoId":[UserInfoSave shareInstance].uid?:@""};
    
    [ZNetworkService uploadImage:array url:kUploadUrl parameters:@{} success:^(id result) {
        
        YYLog(@"%@",result);
        
    } fail:^(NSError *error) {
        
        YYLog(@"%@",error);
        
    } delegater:nil];
    
//    [NNetworkClient uploadImage:array url:kUploadUrl parameters:dict success:^(id responseObject) {
//
//        YYLog(@"%@",responseObject);
//        //
//        if ([responseObject[@"code"] isEqualToString:@"0"]) {
//
//            //接收返回的url 进行回显
////            NSString *url = responseObject[@"page"];
////            self.headImgUrl = url;
//            [self.tableView reloadData];
//
//        }
//
//    } fail:^(NSError *error) {
//
//        YYLog(@"%@",error);
//
//    } delegater:nil];
    
    
    NSLog(@"%@",info);
    [picker dismissViewControllerAnimated:YES completion:^{
        NSLog(@"选照片");
    }];
    
}

#pragma mark - zfimage  delegate 相册拍照

- (void)clickAction:(ZFActionSheet *)actionSheet atIndex:(NSUInteger)index
{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
    imagePicker.allowsEditing = YES;
    if (index==0) {
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    if (index==1) {
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    }

    imagePicker.delegate = self;
    [self presentViewController:imagePicker animated:YES completion:^{
        NSLog(@"打开相册");
    }];
    }

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    

    ZNickAddSchoolLikeVC *nick = [[ZNickAddSchoolLikeVC alloc]initWithNibName:@"ZNickAddSchoolLikeVC" bundle:nil];
    
    switch (indexPath.row) {
            
        case 0:
            {
                ZFActionSheet *sheet = [ZFActionSheet actionSheetWithTitle:nil confirms:@[@"相册",@"拍照"] cancel:@"取消" style:ZFActionSheetStyleDefault];
                sheet.delegate = self;
                [sheet show];
//                WeakStament(ws);
              
            }
            break;
        case 1:
        {
            //昵称
            
            nick.ttitle = @"昵称";
            [self.navigationController pushViewController:nick animated:YES];
            
        }
            break;
        case 2:
        {
            //手机号
            
            nick.ttitle = @"手机号";
            [self.navigationController pushViewController:nick animated:YES];
            
        }
            break;
        case 3:
        {
            //生日
            //时间选择器日期选择器
            [UICustomDatePicker showCustomDatePickerAtView:self.view choosedDateBlock:^(NSDate *date) {
                
                NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
                fmt.dateFormat = @"yyyy-MM-dd";
                NSString *string = [fmt stringFromDate:date];
//                self.birthLael.text =  string;
                YYLog(@"current Date:%@",string);
                [UserInfoSave shareInstance].birthday = string;
                [[NSUserDefaults standardUserDefaults]setObject:string forKey:@"birthday"];
                [[NSUserDefaults standardUserDefaults]synchronize];
                ///
                [self updateMsgWithTitle:@"birthday" andMsg:string];
                
                ///刷新某一行
                NSIndexPath *indexPath=[NSIndexPath indexPathForRow:3 inSection:0];
                [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
                
//                [NGlobalModel shareInstance].birth = string;
            } cancelBlock:^{
                
            }];
            
        }
            break;
        case 4:
        {
            NSMutableArray *data = [NSMutableArray arrayWithArray:@[@"男",@"女",]];
            STPickerSingle *single = [[STPickerSingle alloc]init];
            single.tag = 121;
            [single setArrayData:data];
            [single setTitleUnit:@""];
            [single setDelegate:self];
            [single show];
        }
            break;
        case 5:
        {
            
            //地区选择器
            self.pickerView = [[GFAddressPicker alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-64)];
            [self.pickerView updateAddressAtProvince:@"北京市" city:@"北京市" town:@"东城区"];
            self.pickerView.delegate = self;
            self.pickerView.font = [UIFont boldSystemFontOfSize:18];
            [self.view addSubview:self.pickerView];
//            [ZJUsefulPickerView showCitiesPickerWithToolBarText:@"省市区选择" withDefaultSelectedValues:@[@"四川", @"成都", @"郫县"] withCancelHandler:^{
//                NSLog(@"quxiaole -----");
//
//            } withDoneHandler:^(NSArray *selectedValues) {
//                NSLog(@"%@---", selectedValues);
//
//            }];
            
        }
            break;
        case 6:
        {
            nick.ttitle = @"详细地址";
            [self.navigationController pushViewController:nick animated:YES];
        }
            break;
        case 7:
        {
            nick.ttitle = @"学校";
            [self.navigationController pushViewController:nick animated:YES];
        }
            break;
        case 8:
        {
            NSMutableArray *data = [NSMutableArray arrayWithArray:@[@"一年级",@"二年级",@"三年级",@"四年级",@"五年级",@"六年级",@"七年级",@"九年级",@"十年级",@"十一年级",@"十二年级",@"十三"]];
            STPickerSingle *single = [[STPickerSingle alloc]init];
            single.tag = 122;
            [single setArrayData:data];
            [single setTitleUnit:@""];
            [single setDelegate:self];
            [single show];
        }
            break;
        case 9:
        {
            nick.ttitle = @"爱好";
            [self.navigationController pushViewController:nick animated:YES];
        }
            break;
            
            
        default:
            break;
    }
}



#pragma - STpickerdelegate
///
- (void)pickerSingle:(STPickerSingle *)pickerSingle selectedTitle:(NSString *)selectedTitle selectIndex:(NSInteger)selectIndex{

    switch (pickerSingle.tag) {
        case 121:
        {
            YYLog(@"性别：%@",selectedTitle);
            if ([selectedTitle isEqualToString:@"男"]) {
                [UserInfoSave shareInstance].gender = @"1";
            }else{
                [UserInfoSave shareInstance].gender = @"2";
            }
            ///刷新某一行
            NSIndexPath *indexPath=[NSIndexPath indexPathForRow:4 inSection:0];
            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
            
        }
            break;
        case 122:
        {
            [UserInfoSave shareInstance].grade = selectedTitle;
            [[NSUserDefaults standardUserDefaults]setObject:selectedTitle forKey:@"grade"];
            [[NSUserDefaults standardUserDefaults]synchronize];
            
            [self updateMsgWithTitle:@"grade" andMsg:selectedTitle];
            ///刷新某一行
            NSIndexPath *indexPath=[NSIndexPath indexPathForRow:8 inSection:0];
            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        }
            
        default:
            break;
    }

}


#pragma mark - 地区选择器delegate

- (void)GFAddressPickerCancleAction
{
    [self.pickerView removeFromSuperview];
}

- (void)GFAddressPickerWithProvince:(NSString *)province
                               city:(NSString *)city area:(NSString *)area
{
    
    [self.pickerView removeFromSuperview];
    YYLog(@"%@  %@  %@",province,city,area);
    [UserInfoSave shareInstance].area = [NSString stringWithFormat:@"%@ %@ %@",province,city,area];
    
    [[NSUserDefaults standardUserDefaults]setObject:[UserInfoSave shareInstance].area forKey:@"area"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    YYLog(@"%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"area"]);
    
     [self updateMsgWithTitle:@"province" andMsg:province];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self updateMsgWithTitle:@"city" andMsg:city];
    });
   
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
         [self updateMsgWithTitle:@"area" andMsg:area];
    });
   
    ///刷新某一行
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:5 inSection:0];
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
}


///
-(void)updateMsgWithTitle:(NSString *)title andMsg:(NSString *)msg{
    
    
   NSDictionary * dic =@{@"id":[UserInfoSave shareInstance].uid?:@"",title:msg?:@""};
    
    [ZNetworkService postRequestWithBaseUrl:kUpdateUserMsgUrl setParameters:dic success:^(id result) {
        YYLog(@"%@",result);
        if ([result[@"errorCode"]integerValue]==0) {
//            [SVProgressHUD dismiss];
//            NSDictionary *userDict = result[@"result"];
//            [UserInfoSave shareInstance].school = userDict[@"school"];
//            YYLog(@"%@",[UserInfoSave shareInstance].school);
//            [[NSUserDefaults standardUserDefaults]setObject:userDict[@"school"] forKey:@"school"];
//            [[NSUserDefaults standardUserDefaults]synchronize];
//            [ws.navigationController popViewControllerAnimated:YES];
//            [AFToast showText:@"修改成功"];
            
        }
    } fail:^(NSError *error) {
        YYLog(@"%@",error);
    } delegater:nil];
}
@end
